var app = getApp();
var server = require('server');
/**
 * 协议获取
 */
function getcontract() {
  var userid = app.globalData.userInfo.userid;
  server.postJSON("getUserContract?userid=" + userid, function(res) {
    return res;
  })

}
/**
 * 判断是否已经获取到用户信息
 */
function openidsaved() {
  app.getOpenId(function() {
    var openid = app.globalData.openid;
    var unionid = app.globalData.unionid;
    var parameter = {
      openid: openid,
      unionid: unionid
    };
    //判断是否存在经纬度
    if (app.globalData.longitude != undefined && app.globalData.latitude != undefined) {
      var longitude = app.globalData.longitude
      var latitude = app.globalData.latitude
      parameter = {
        openid: openid,
        unionid: unionid,
        lng: longitude,
        lat: latitude
      }
    }
    server.getJSON("openidsaved", parameter, function(res) {
      if (res.data.data == null) {
        app.register();
      } else {
        var userInfo = res.data.data;
        userPersonalCenter(userInfo.userid);
      }
    });
  });
}
/**
 * 获取用户信息
 */
function userPersonalCenter(userid) {
  //接口及条件
  var parameter = "userPersonalCenter?userid=" + userid;
  server.postJSON(parameter, function(res) {
    var usersuccess = res.data.success;
    if (usersuccess == true) {
      var userPersonalCenter = res.data.data.userPersonalCenter[0]
      app.globalData.userInfo = userPersonalCenter;
    }
  })
}
/**
 * 页面弹框（选择提示,单按钮）
 */
function showCloseModel(title, content) {
  wx.showModal({
    title: title,
    content: content,
    showCancel: false,
    confirmText: '关闭',
    confirmColor: '#000000',
    success: function(res) {},
    fail: function(res) {},
    complete: function(res) {},
  })
}
/**
 * 页面弹框（成功提示）
 */
function showOkToast(str) {
  wx.showToast({
    title: str,
    icon: '',
    image: '/images/success-1.png',
    duration: 2000,
    mask: true,
    success: function(res) {},
    fail: function(res) {},
    complete: function(res) {},
  })
}
/**
 * 判断用户是否已经实名认证
 */
function approveflag() {
  var userInfo = app.globalData.userInfo;
  if (userInfo.approveflag == 0) {
    return 0;
  }
  if (userInfo.approveflag == 1) {
    return 1;
  }
  if (userInfo.approveflag == 2) {
    return 2
  }
}
/**
 * 去实名认证
 * url：要跳转的地址(如：./identity/identity)
 * parameter:所要传的参数（如：?userid=1&openid=lksdjfkdsfdsf）
 */
function identity(url, parameter = '') {
  if (parameter) {
    url = url + parameter;
  }
  wx.showModal({
    title: ' ',
    content: '请先进行身份认证',
    confirmText: '去认证',
    cancelText: '取消',
    success: function(res) {
      if (res.confirm) {
        wx.navigateTo({
          url: url,
        })
      }
      if (res.cancel) {
        showOkToast('取消成功！');
      }
    },
    fail: function(res) {
      showErrorToast('操作失败！');
    },
    complete: function(res) {},
  })
}
/**
 * 页面弹框（失败提示）
 */
function showErrorToast(str) {
  wx.showToast({
    title: str,
    icon: '',
    image: '/img/base/error-1.png',
    duration: 2000,
    mask: true,
    success: function(res) {},
    fail: function(res) {},
    complete: function(res) {},
  })
}

/**
 * 判断是否为中文
 */
function IsChinese(str) {
  var reg = /^[\u0391-\uFFE5]+$/;
  if (reg.test(str)) {
    return true;
  } else {
    return false;
  }
}
/*
 *电话校验
 */
function checkPhoneNum(phoneNumber) {
  let str = /^1[3456789][0-9]{9}$/
  if (str.test(phoneNumber)) {
    return true;
  } else {
    return false;
  }
}
/**
 * 校验邮箱
 */
function checkEmail(email) {
  let str = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
  if (str.test(email)) {
    return true
  } else {
    return false
  }
}
/**
 * 判断是否为纸币
 */
function isMoney(money) {
  var str = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
  if (str.test(money)) {
    return true;
  } else {
    return false;
  }
}
/**
 * 判断身份证号码
 * numberstr：身份证号码
 */
function checkIdcode(idcode) {
  var str = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/
  if (str.test(idcode)) {
    return true;
  } else {
    return false;
  }
}
/**
 * 日期验证
 */
function checkBirthday(birthday) {
  var str = /(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)/
  if (str.test(birthday)) {
    return true;
  } else {
    return false;
  }
}
/**
 * 去控格
 */
function Trim(str, is_global) {
  var result;
  result = str.replace(/(^\s+)|(\s+$)/g, "");
  if (is_global.toLowerCase() == "g") {
    result = result.replace(/\s/g, "");
  }
  return result;
}
/**
 * 判断是否为数字
 */
function isNumber(numberstr) {
  var regNum = new RegExp('[0-9]', 'g'); //判断用户输入的是否为数字
  var isnumber = regNum.test(numberstr);
  if (isnumber) {
    return true;
  } else {
    return false;
  }
}
/**
 * 显示距离
 * distance:传入的数number
 */
function showDistance(distance) {
  var intdistance = parseInt(distance);
  if (intdistance < 1000 && 0 <= intdistance) {
    return intdistance + '米';
  } else {
    return (intdistance / 1000).toFixed(2) + '千米';
  }
}
/**
 * 时间转换为时间戳
 * day: 传入的时间
 */
function numberDay(day) {
  var numberDay = Date.parse(new Date(day));
  numberDay = numberDay / 1000;
  return numberDay;
}
/** 
 * 时间戳转化为年 月 日 时 分 秒 
 * number: 传入时间戳 
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
 */
function formatTime(number, format) {
  var formateArr = ['Y', 'M', 'D', 'h', 'i', 's'];
  var returnArr = [];

  var date = new Date(number * 1000);

  returnArr.push(date.getFullYear());

  returnArr.push(formatNumber(date.getMonth() + 1));

  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));

  returnArr.push(formatNumber(date.getMinutes()));

  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {

    format = format.replace(formateArr[i], returnArr[i]);

  }

  return format;

}
/**
 * 定时器
 * that 当前位置
 * count 定时时间
 * num 多少时间定时一次
 */
function countdown(that,count = 60,num = 1000) {
  var second = count;
  var appcount; 
  that.setDateFlag(1)
  appcount = setInterval(function () {
    second = second - 1;
    if (second < 1) {
      clearInterval(appcount); //取消指定的setInterval函数将要执行的代码
      that.setDateFlag(2)
    }
    that.setDate(second);
  }, num);
}
/**
 * formatTime()：方法调用
 * n：传入的数据（number）
 */
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
/**
 * 获取某一时刻
 * today： 不填默认为今天时间
 * numberDay：与某一时刻相隔显示的格式
 * count：获取与某一时刻相隔的时间默认为0
 * format：返回的格式
 */
function getDateStr(today = '', formatDay = 's', count = 0, format = 'Y年M月D日 h:i:s') {
  var dd;
  if (today) {
    dd = new Date(today);
  } else {
    dd = new Date();
  }
  if (formatDay == 'Y') {
    var dateNumber = dd.setFullYear(dd.getFullYear() + count);
    dd = new Date(dateNumber);
  } else if (formatDay == 'M') {
    var dateNumber = dd.setMonth(dd.getMonth() + count);
    dd = new Date(dateNumber);
  } else if (formatDay == 'D') {
    dd.setDate(dd.getDate() + count); //获取count后的时间
  } else if (formatDay == 'h') {
    var dateNumber = dd.setHours(dd.getHours() + count);
    dd = new Date(dateNumber);
  } else if (formatDay == 'i') {
    var dateNumber = dd.setMinutes(dd.getMinutes() + count);
    dd = new Date(dateNumber);
  } else if (formatDay == 's') {
    var dateNumber = dd.setSeconds(dd.getSeconds() + count);
    dd = new Date(dateNumber);
  } else {
    var dateNumber = dd.setSeconds(dd.getSeconds() + count);
    dd = new Date(dateNumber);
  }
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1; //获取当前月份的日期
  var d = dd.getDate();
  var hour = dd.getHours()
  var minute = dd.getMinutes()
  var second = dd.getSeconds()
  var formateArr = ['Y', 'M', 'D', 'h', 'i', 's'];
  var returnArr = [];
  returnArr.push(y);
  returnArr.push(formatNumber(m));
  returnArr.push(formatNumber(d));
  returnArr.push(formatNumber(hour));
  returnArr.push(formatNumber(minute));
  returnArr.push(formatNumber(second));
  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
module.exports = {
  openidsaved: openidsaved,
  userPersonalCenter: userPersonalCenter,
  isNumber: isNumber,
  showCloseModel: showCloseModel,
  showOkToast: showOkToast,
  showErrorToast: showErrorToast,
  IsChinese: IsChinese,
  checkPhoneNum: checkPhoneNum,
  checkEmail: checkEmail,
  showDistance: showDistance,
  isMoney: isMoney,
  isNumber: isNumber,
  Trim: Trim,
  numberDay: numberDay,
  formatTime: formatTime,
  getDateStr: getDateStr,
  formatNumber: formatNumber,
  approveflag: approveflag,
  identity: identity,
  checkIdcode: checkIdcode,
  checkBirthday: checkBirthday,
  getcontract: getcontract,
  countdown: countdown,
}